# -*- coding: utf-8 -*-
# @Time    : 2020/6/7 10:14
# @Author  : Leeli
# @Email   : lililove2000@163.com
# @File    : main.py
# @Software: PyCharm

from time import strftime  # 导入time的strftime方法

from kivy.app import App  # 导入Kivy的App基类
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout  # 导入布局


# 布局类
class ClockBoxLayout(BoxLayout):
    # 初始化
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.timing_flag = False
        self.timing_seconds = 0  # 声明一个变量（分钟）
        self.on_start()

    def update_time(self, nap):
        if self.timing_flag:
            self.timing_seconds = self.timing_seconds + nap  # 累计时间（分钟）

        # 通过ID获取time_label_id控件，并设置text的属性值
        self.ids.time_label_id.text = strftime("[b]%H[/b]:%M:%S")
        m, s = divmod(self.timing_seconds, 60)
        # 通过ID获取stopwatch控件，并设置text的属性值
        self.ids.stopwatch.text = ("%02d:%02d.[size=40]%02d[/size]" % (int(m), int(s), int(s * 100 % 100)))

    def on_start(self):
        # 每0秒执行一次update_time()方法
        Clock.schedule_interval(self.update_time, 0)

    def start_or_stop(self):
        # 切换按钮状态
        """
        if self.timing_flag:
            self.ids.start_stop_button_id.text = "Start"
        else:
            self.ids.start_stop_button_id.text = "Stop"
        代码简写为
        self.ids.start_stop_button_id.text = "Start" if self.timing_flag else "Stop"
        """
        self.ids.start_stop_button_id.text = "开始计时" if self.timing_flag else "停止计时"
        self.timing_flag = not self.timing_flag


# 继承App类
class ClockApp(App):
    def build(self):
        # 返回根控件
        return ClockBoxLayout()


if __name__ == "__main__":  # 程序入口
    from kivy.core.window import Window

    Window.clearcolor = [0.8, 0.8, 0.8, 1]
    ClockApp().run()  # 启动应用程序
